/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.modules.system.domain.WxUser;
import me.zhengjie.modules.system.domain.WxUserCourse;
import me.zhengjie.modules.system.service.WxUserService;
import me.zhengjie.modules.web.domain.pay.OrderSubmitRequest;
import me.zhengjie.modules.web.domain.pay.OrderSubmitResponse;
import me.zhengjie.modules.web.service.pay.OrderSubmitFactory;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.WxUserCourseRepository;
import me.zhengjie.modules.system.service.WxUserCourseService;
import me.zhengjie.modules.system.service.dto.WxUserCourseDto;
import me.zhengjie.modules.system.service.dto.WxUserCourseQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.WxUserCourseMapper;
import me.zhengjie.utils.enums.OrderTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wangyu
* @date 2024-03-13
**/
@Service
@RequiredArgsConstructor
public class WxUserCourseServiceImpl implements WxUserCourseService {

    private final WxUserCourseRepository wxUserCourseRepository;
    private final WxUserCourseMapper wxUserCourseMapper;

    @Autowired
    private WxUserService wxUserService;

    @Override
    public Map<String,Object> queryAll(WxUserCourseQueryCriteria criteria, Pageable pageable){
        Page<WxUserCourse> page = wxUserCourseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(wxUserCourseMapper::toDto));
    }

    @Override
    public List<WxUserCourseDto> queryAll(WxUserCourseQueryCriteria criteria){
        return wxUserCourseMapper.toDto(wxUserCourseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public WxUserCourseDto findById(Long userCourseId) {
        WxUserCourse wxUserCourse = wxUserCourseRepository.findById(userCourseId).orElseGet(WxUserCourse::new);
        ValidationUtil.isNull(wxUserCourse.getUserCourseId(),"WxUserCourse","userCourseId",userCourseId);
        return wxUserCourseMapper.toDto(wxUserCourse);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WxUserCourseDto create(WxUserCourse resources) {
        resources.setCreateTime(DateUtil.TimestampNow());
        resources.setCreateby(SecurityUtils.getCurrentUsername());
        WxUserCourseDto wxUserCourseDto = wxUserCourseMapper.toDto(wxUserCourseRepository.save(resources));
        if (Objects.isNull(wxUserCourseDto)){
            return null;
        }
        WxUser wxUser = wxUserService.findByOpenId(resources.getOpenId());
        OrderSubmitRequest requestEntity = new OrderSubmitRequest();
        requestEntity.setCourseNo(resources.getCourseNo());
        requestEntity.setOrderType(OrderTypeEnum.Course.getOrderType());
        requestEntity.setBackendOpenId(resources.getOpenId());
        requestEntity.setNotNeedPay(true);
        List<OrderSubmitRequest.CourseApplicantsRequest> courseApplicantsRequests = new ArrayList<>();
        OrderSubmitRequest.CourseApplicantsRequest applicantsRequest = new OrderSubmitRequest.CourseApplicantsRequest();
        applicantsRequest.setMobile(wxUser.getMobile());
        applicantsRequest.setRealName(wxUser.getRealName());
        courseApplicantsRequests.add(applicantsRequest);
        requestEntity.setApplicantsList(courseApplicantsRequests);
        OrderSubmitResponse execute = OrderSubmitFactory.orderType(requestEntity.getOrderType()).execute(requestEntity);
        return wxUserCourseDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(WxUserCourse resources) {
        resources.setUpdateby(SecurityUtils.getCurrentUsername());
        resources.setUpdateTime(DateUtil.TimestampNow());
        WxUserCourse wxUserCourse = wxUserCourseRepository.findById(resources.getUserCourseId()).orElseGet(WxUserCourse::new);
        ValidationUtil.isNull( wxUserCourse.getUserCourseId(),"WxUserCourse","id",resources.getUserCourseId());
        wxUserCourse.copy(resources);
        wxUserCourseRepository.save(wxUserCourse);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long userCourseId : ids) {
            wxUserCourseRepository.deleteById(userCourseId);
        }
    }

    @Override
    public void download(List<WxUserCourseDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (WxUserCourseDto wxUserCourse : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户openId", wxUserCourse.getOpenId());
            map.put("课程名称", wxUserCourse.getCourseName());
            map.put("课程编号", wxUserCourse.getCourseNo());
            map.put("创建时间", wxUserCourse.getCreateTime());
            map.put("创建人", wxUserCourse.getCreateby());
            map.put("更新时间", wxUserCourse.getUpdateTime());
            map.put("更新人", wxUserCourse.getUpdateby());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}